package top.yokey.shopai.goods.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Objects;

import top.yokey.shopai.R;
import top.yokey.shopai.goods.adapter.GoodsBuyCouponAdapter;
import top.yokey.shopai.goods.adapter.GoodsBuyStoreAdapter;
import top.yokey.shopai.goods.viewmodel.GoodsBuyVM;
import top.yokey.shopai.zcom.App;
import top.yokey.shopai.zcom.arouter.ARoutePath;
import top.yokey.shopai.zcom.base.BaseActivity;
import top.yokey.shopai.zcom.help.DialogHelp;
import top.yokey.shopai.zcom.help.ToastHelp;
import top.yokey.shopai.zcom.other.Constant;
import top.yokey.shopai.zcom.recycler.LineDecoration;
import top.yokey.shopai.zcom.util.AnimUtil;
import top.yokey.shopai.zcom.util.ConvertUtil;
import top.yokey.shopai.zcom.util.JsonUtil;
import top.yokey.shopai.zcom.util.VerifyUtil;
import top.yokey.shopai.zsdk.bean.BuyCouponBean;
import top.yokey.shopai.zsdk.bean.BuyStoreBean;
import top.yokey.shopai.zsdk.data.GoodsBuyData;

@Route(path = ARoutePath.GOODS_BUY)
public class GoodsBuyActivity extends BaseActivity {

    private final ArrayList<BuyStoreBean> arrayList = new ArrayList<>();
    private final GoodsBuyStoreAdapter adapter = new GoodsBuyStoreAdapter(arrayList);
    private final ArrayList<BuyCouponBean> couponArrayList = new ArrayList<>();
    private final GoodsBuyCouponAdapter couponAdapter = new GoodsBuyCouponAdapter(couponArrayList);
    @Autowired(name = Constant.DATA_JSON)
    String json = "";
    private Toolbar mainToolbar = null;
    private RelativeLayout addressRelativeLayout = null;
    private AppCompatTextView addressNameTextView = null;
    private AppCompatTextView addressAreaTextView = null;
    private AppCompatTextView onlineTextView = null;
    private AppCompatTextView offlineTextView = null;
    private AppCompatTextView invoiceNoTextView = null;
    private AppCompatTextView invoiceYesTextView = null;
    private RelativeLayout discountRelativeLayout = null;
    private View couponView = null;
    private LinearLayoutCompat couponLinearLayout = null;
    private AppCompatTextView couponTextView = null;
    private View pointView = null;
    private LinearLayoutCompat pointLinearLayout = null;
    private AppCompatEditText pointEditText = null;
    private RecyclerView mainRecyclerView = null;
    private AppCompatTextView settlementTextView = null;
    private AppCompatTextView submitTextView = null;
    private AppCompatTextView nightTextView = null;
    private RecyclerView couponRecyclerView = null;
    private int point = 0;
    private double parity = 0.0f;
    private double amount = 0.0f;
    private GoodsBuyData data = null;
    private GoodsBuyVM vm = null;

    @Override
    public void initView() {

        setContentView(R.layout.activity_goods_buy);
        mainToolbar = findViewById(R.id.mainToolbar);
        addressRelativeLayout = findViewById(R.id.addressRelativeLayout);
        addressNameTextView = findViewById(R.id.addressNameTextView);
        addressAreaTextView = findViewById(R.id.addressAreaTextView);
        onlineTextView = findViewById(R.id.onlineTextView);
        offlineTextView = findViewById(R.id.offlineTextView);
        invoiceNoTextView = findViewById(R.id.invoiceNoTextView);
        invoiceYesTextView = findViewById(R.id.invoiceYesTextView);
        discountRelativeLayout = findViewById(R.id.discountRelativeLayout);
        couponView = findViewById(R.id.couponView);
        couponLinearLayout = findViewById(R.id.couponLinearLayout);
        couponTextView = findViewById(R.id.couponTextView);
        pointView = findViewById(R.id.pointView);
        pointLinearLayout = findViewById(R.id.pointLinearLayout);
        pointEditText = findViewById(R.id.pointEditText);
        settlementTextView = findViewById(R.id.settlementTextView);
        submitTextView = findViewById(R.id.submitTextView);
        mainRecyclerView = findViewById(R.id.mainRecyclerView);
        nightTextView = findViewById(R.id.nightTextView);
        couponRecyclerView = findViewById(R.id.couponRecyclerView);

    }

    @Override
    public void initData() {

        if (VerifyUtil.isEmpty(json)) {
            ToastHelp.get().showDataError();
            onReturn(false);
            return;
        }
        data = JsonUtil.json2Object(json, GoodsBuyData.class);
        if (data.getIfcart().equals("1") && !VerifyUtil.isEmpty(data.getPingou())) {
            ToastHelp.get().showDataError();
            onReturn(false);
            return;
        }
        setToolbar(mainToolbar, R.string.confirmOrderInfo);
        observeKeyborad(R.id.mainRelativeLayout);
        App.get().setRecyclerView(mainRecyclerView, adapter);
        App.get().setRecyclerView(couponRecyclerView, couponAdapter);
        mainRecyclerView.addItemDecoration(new LineDecoration(App.get().dp2Px(12), true));
        couponRecyclerView.addItemDecoration(new LineDecoration(App.get().dp2Px(16), true));
        vm = getVM(GoodsBuyVM.class);
        vm.buyStep1(data);

    }

    @Override
    public void initEvent() {

        addressRelativeLayout.setOnClickListener(view -> App.get().start(get(), ARoutePath.MEMBER_ADDRESS, Constant.DATA_ID, Constant.COMMON_ENABLE, Constant.CODE_ADDRESS));

        onlineTextView.setOnClickListener(view -> {
            data.setPayName("online");
            onlineTextView.setTextColor(App.get().getColors(R.color.primary));
            onlineTextView.setBackgroundResource(R.drawable.selector_accent_16dp);
            offlineTextView.setTextColor(App.get().getColors(R.color.accent));
            offlineTextView.setBackgroundResource(R.drawable.selector_hollow_accent_16dp);
        });

        offlineTextView.setOnClickListener(view -> {
            data.setPayName("offline");
            onlineTextView.setTextColor(App.get().getColors(R.color.accent));
            onlineTextView.setBackgroundResource(R.drawable.selector_hollow_accent_16dp);
            offlineTextView.setTextColor(App.get().getColors(R.color.primary));
            offlineTextView.setBackgroundResource(R.drawable.selector_accent_16dp);
        });

        invoiceNoTextView.setOnClickListener(view -> {
            data.setInvoiceId("");
            invoiceYesTextView.setText(R.string.needInvoice);
            invoiceNoTextView.setTextColor(App.get().getColors(R.color.primary));
            invoiceNoTextView.setBackgroundResource(R.drawable.selector_accent_16dp);
            invoiceYesTextView.setTextColor(App.get().getColors(R.color.accent));
            invoiceYesTextView.setBackgroundResource(R.drawable.selector_hollow_accent_16dp);
        });

        invoiceYesTextView.setOnClickListener(view -> App.get().start(get(), ARoutePath.MEMBER_INVOICE, Constant.DATA_ID, Constant.COMMON_ENABLE, Constant.CODE_INVOICE));

        pointEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int value = ConvertUtil.string2Int(Objects.requireNonNull(pointEditText.getText()).toString());
                if (value > point) {
                    value = point;
                    String temp = value + "";
                    pointEditText.setText(temp);
                    pointEditText.setSelection(temp.length());
                }
                data.setjPointInput(value + "");
                setSettlement(amount - (value * parity));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        couponLinearLayout.setOnClickListener(view -> {
            if (couponArrayList.size() == 0) {
                ToastHelp.get().show(R.string.tipsNoHaveCoupon);
                return;
            }
            show();
        });

        submitTextView.setOnClickListener(view -> {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < arrayList.size(); i++) {
                stringBuilder.append(arrayList.get(i).getKey()).append("|").append(arrayList.get(i).getMessage()).append(",");
            }
            data.setPayMessage(stringBuilder.toString());
            submitTextView.setText(R.string.handlerIng);
            submitTextView.setEnabled(false);
            vm.buyStep2(data);
        });

        couponAdapter.setOnItemClickListener((position, bean) -> {
            couponTextView.setText(String.format(getString(R.string.goodsBuyCoupon), bean.getCouponLimit(), bean.getCouponPrice()));
            data.setRpt(bean.getCouponTId() + "|" + bean.getCouponPrice());
            gone();
        });

        nightTextView.setOnClickListener(view -> gone());

    }

    @Override
    public void initObserve() {

        vm.getStep1LiveData().observe(this, string -> {
            arrayList.clear();
            JSONObject jsonObject;
            BuyStoreBean storeBuyBean;
            Iterator<String> iterator;
            string = string.replace("[]", "null");
            JSONObject mainJsonObject = JsonUtil.toJSONObject(string);
            JSONObject addressInfoJSONObject = JsonUtil.getJSONObject(mainJsonObject, "address_info");
            JSONObject addressApiJSONObject = JsonUtil.getJSONObject(mainJsonObject, "address_api");
            //地址信息
            if (Objects.requireNonNull(addressInfoJSONObject).toString().equals("{}")) {
                tipsAddAddress();
                return;
            }
            addressNameTextView.setText(JsonUtil.getString(addressInfoJSONObject, "true_name"));
            addressNameTextView.append(" " + JsonUtil.getString(addressInfoJSONObject, "mob_phone"));
            addressAreaTextView.setText(JsonUtil.getString(addressInfoJSONObject, "area_info"));
            addressAreaTextView.append(" " + JsonUtil.getString(addressInfoJSONObject, "address"));
            //支付方式
            offlineTextView.setVisibility(View.GONE);
            if (JsonUtil.getBoolean(mainJsonObject, "ifshow_offpay") && JsonUtil.getString(addressApiJSONObject, "allow_offpay").equals("1")) {
                offlineTextView.setVisibility(View.VISIBLE);
            }
            //平台优惠券
            couponArrayList.clear();
            couponView.setVisibility(View.GONE);
            couponLinearLayout.setVisibility(View.GONE);
            couponTextView.setText(R.string.tipsNoHaveCoupon);
            String rptList = JsonUtil.getString(mainJsonObject, "rpt_list");
            if (!VerifyUtil.isEmpty(rptList) && !rptList.equals("null") && !rptList.equals("[]")) {
                couponView.setVisibility(View.VISIBLE);
                couponLinearLayout.setVisibility(View.VISIBLE);
                couponArrayList.addAll(JsonUtil.json2ArrayList(rptList, BuyCouponBean.class));
                couponTextView.setText(String.format(getString(R.string.canUseCoupon), couponArrayList.size() + ""));
                couponAdapter.notifyDataSetChanged();
            }
            //积分抵扣
            pointView.setVisibility(View.GONE);
            pointLinearLayout.setVisibility(View.GONE);
            point = JsonUtil.getInt(mainJsonObject, "member_points");
            parity = JsonUtil.getDouble(mainJsonObject, "points_money_parity");
            if (JsonUtil.getString(mainJsonObject, "points_money_isuse").equals(Constant.COMMON_ENABLE) && point != 0) {
                pointView.setVisibility(View.VISIBLE);
                pointLinearLayout.setVisibility(View.VISIBLE);
                pointEditText.setHint(String.format(getString(R.string.goodsBuyPoint), parity + "", point + ""));
            }
            //优惠信息
            discountRelativeLayout.setVisibility(View.VISIBLE);
            if (couponView.getVisibility() == View.GONE && pointView.getVisibility() == View.GONE) {
                discountRelativeLayout.setVisibility(View.GONE);
            }
            //店铺列表
            jsonObject = JsonUtil.getJSONObject(mainJsonObject, "store_cart_list");
            iterator = Objects.requireNonNull(jsonObject).keys();
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = JsonUtil.getString(jsonObject, key);
                storeBuyBean = JsonUtil.json2Object(value, BuyStoreBean.class);
                storeBuyBean.setKey(key);
                arrayList.add(storeBuyBean);
            }
            //店铺代金券
            jsonObject = JsonUtil.getJSONObject(addressApiJSONObject, "content");
            iterator = Objects.requireNonNull(jsonObject).keys();
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = JsonUtil.getString(jsonObject, key);
                for (int i = 0; i < arrayList.size(); i++) {
                    if (arrayList.get(i).getKey().equals(key)) {
                        arrayList.get(i).setLogistics(value);
                    }
                }
            }
            //店铺总计
            jsonObject = JsonUtil.getJSONObject(mainJsonObject, "store_final_total_list");
            iterator = Objects.requireNonNull(jsonObject).keys();
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = JsonUtil.getString(jsonObject, key);
                for (int i = 0; i < arrayList.size(); i++) {
                    if (arrayList.get(i).getKey().equals(key)) {
                        arrayList.get(i).setTotal(value);
                    }
                }
            }
            //结算金额
            amount = JsonUtil.getDouble(mainJsonObject, "order_amount");
            adapter.notifyDataSetChanged();
            setSettlement(amount);
            //提交信息
            data.setAddressId(JsonUtil.getString(addressInfoJSONObject, "address_id"));
            data.setVatHash(JsonUtil.getString(mainJsonObject, "vat_hash"));
            data.setOffpayHash(JsonUtil.getString(addressApiJSONObject, "offpay_hash"));
            data.setOffpayHashBatch(JsonUtil.getString(addressApiJSONObject, "offpay_hash_batch"));
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < arrayList.size(); i++) {
                if (arrayList.get(i).getStoreVoucherInfo() != null) {
                    stringBuilder.append(arrayList.get(i).getStoreVoucherInfo().getVoucherTId())
                            .append("|").append(arrayList.get(i).getStoreVoucherInfo().getVoucherStoreId())
                            .append("|").append(arrayList.get(i).getStoreVoucherInfo().getVoucherPrice())
                            .append(",");
                }
            }
            string = stringBuilder.toString();
            data.setVoucher(string);
        });

        vm.getStep2LiveData().observe(this, string -> {
            String code = JsonUtil.getString(string, "payment_code");
            if (code.equals("online")) {
                App.get().start(ARoutePath.ORDER_PAY, Constant.DATA_SN, JsonUtil.getString(string, "pay_sn"));
                onReturn(false);
                return;
            }
            App.get().start(ARoutePath.ORDER_LIST, Constant.DATA_POSITION, 2);
            onReturn(false);
        });

        vm.getErrorLiveData().observe(this, bean -> {
            if (bean.getCode() == 1) {
                DialogHelp.get().query(get(), R.string.loadFailure, bean.getReason(), view -> onReturn(false), view -> vm.buyStep1(data));
            } else {
                submitTextView.setEnabled(true);
                submitTextView.setText(R.string.submitOrder);
                ToastHelp.get().show(bean.getReason());
            }
        });

    }

    @Override
    public void onReturn(boolean handler) {

        if (nightTextView.getVisibility() == View.VISIBLE) {
            gone();
            return;
        }
        if (handler && isShowKeyboard()) {
            hideKeyboard();
            return;
        }
        finish();

    }

    @Override
    public void onActivityResult(int req, int res, @Nullable Intent intent) {

        super.onActivityResult(req, res, intent);
        if (intent != null && res == RESULT_OK) {
            switch (req) {
                case Constant.CODE_ADDRESS:
                    data.setAddressId(intent.getStringExtra(Constant.DATA_ID));
                    vm.buyStep1(data);
                    break;
                case Constant.CODE_INVOICE:
                    data.setInvoiceId(intent.getStringExtra(Constant.DATA_ID));
                    invoiceYesTextView.setText(intent.getStringExtra(Constant.DATA_CONTENT));
                    invoiceNoTextView.setTextColor(App.get().getColors(R.color.accent));
                    invoiceNoTextView.setBackgroundResource(R.drawable.selector_hollow_accent_16dp);
                    invoiceYesTextView.setTextColor(App.get().getColors(R.color.primary));
                    invoiceYesTextView.setBackgroundResource(R.drawable.selector_accent_16dp);
                    break;
            }
        } else {
            if (req == Constant.CODE_ADDRESS) {
                if (VerifyUtil.isEmpty(data.getAddressId())) {
                    tipsAddAddress();
                }
            }
        }

    }

    //自定义方法

    private void gone() {

        if (nightTextView.getVisibility() == View.VISIBLE) {
            AnimUtil.objectAnimator(nightTextView, AnimUtil.ALPHA, () -> nightTextView.setVisibility(View.GONE), 1.0f, 0);
        }
        if (couponRecyclerView.getVisibility() == View.VISIBLE) {
            AnimUtil.objectAnimator(couponRecyclerView, AnimUtil.TRABSLATION_Y, () -> couponRecyclerView.setVisibility(View.GONE), 0, App.get().getHeight());
        }

    }

    private void show() {

        if (nightTextView.getVisibility() == View.GONE) {
            nightTextView.setVisibility(View.VISIBLE);
            AnimUtil.objectAnimator(nightTextView, AnimUtil.ALPHA, 0, 1.0f);
        }
        if (couponRecyclerView.getVisibility() == View.GONE) {
            couponRecyclerView.setVisibility(View.VISIBLE);
            AnimUtil.objectAnimator(couponRecyclerView, AnimUtil.TRABSLATION_Y, App.get().getHeight(), 0);
        }

    }

    private void tipsAddAddress() {

        DialogHelp.get().query(
                get(),
                R.string.loadFailure,
                R.string.tipsAddReceiveAddress,
                view -> onReturn(false),
                view -> App.get().start(get(), ARoutePath.MEMBER_ADDRESS, Constant.DATA_ID, Constant.COMMON_ENABLE, Constant.CODE_ADDRESS)
        );

    }

    private void setSettlement(double price) {

        String temp = String.format(App.get().getString(R.string.htmlBuySettlement), price + "");
        settlementTextView.setText(Html.fromHtml(App.get().handlerHtml(temp, "#EE0000")));

    }

}
